package com.oktest.measure.ui.fragment.home

import android.os.Bundle
import android.util.Log
import android.view.View
import com.cali.common.constant.EventSimple
import com.cali.common.kt.*
import com.cali.libcore.base.BaseFragment
import com.cali.libcore.dialog.alertdialog.helper.CommonDialogHelper
import com.cali.libcore.http.RetrofitManagement
import com.cali.libcore.http.interceptor.DownloadInterceptor
import com.oktest.measure.MyApp
import com.oktest.measure.R
import com.oktest.measure.entity.HomeTaskDetail
import com.oktest.measure.http.Api
import com.oktest.measure.kt.*
import com.oktest.measure.view.NumberProgressBar
import kotlinx.android.synthetic.main.download_data_dialog_layout.view.*
import kotlinx.android.synthetic.main.download_layout_dialog_default.view.*
import kotlinx.android.synthetic.main.fragment_task_detail.*
import kotlinx.coroutines.launch
import java.io.File

/**
 * @Author hhh
 * @Date 2020/9/19
 */
class HomeTaskDetailFragment : BaseFragment() {

    private val dialogHelper by lazy {
        CommonDialogHelper(context!!)
    }

    private var numberProgress: NumberProgressBar? = null

    override fun getLayoutId(): Int {
        return R.layout.fragment_task_detail
    }

    override fun initData(savedInstanceState: Bundle?) {
        toolbarHelper?.setTitleText("作业单详情")
        val taskId = arguments.value(TASK_ID)
        getDetail(taskId)
        initBtnState()
        btnDownload.setOnClickListener {
            showDialog(taskId)
        }
    }

    private fun initBtnState() {
        if (MyApp.currTask()?.isReceived == true) {
            btnDownload.gone()
        } else {
            btnDownload.visible()
        }
    }

    private fun showDialog(taskId: String) {
        val downloadLayout = View.inflate(context, R.layout.download_layout_dialog_default, null)
        downloadLayout?.apply {
            dialogContent.text = "确定下载该任务吗？"
            dialogTitle.text = "温馨提示"
            btnCancel.setOnClickListener {
                dialogHelper.dismiss()
            }
            btnOk.setOnClickListener {
                dialogHelper.dismiss()
                download(taskId)
            }
        }
        dialogHelper.show(downloadLayout, false, isMath = false)
    }

    private fun download(taskId: String) = launch {
        val name = MyApp.roomDatabase.homeTaskDao().query(taskId)?.name?:uuid()
        val xmlFile = File(context?.filesDir, "$name.xml")
        showProgressDialog()
        val downloadInterceptor = DownloadInterceptor{
            Log.i("donwloading","progress=$it")
            numberProgress?.progress = it.toInt()
        }
        val downloadSuccess = successTryContext {
            RetrofitManagement.instance.getDownloadService(Api::class.java, interceptor = downloadInterceptor)
                .download(taskId).execute().body()?.byteStream()?.apply {
                    xmlFile.writeInputStream(this)
                }
        }
        dialogHelper.dismiss()
        if (downloadSuccess) {
            MyApp.currentTaskId = taskId.stringLong()
            // 刷新数据
            MyApp.roomDatabase.homeTaskDao().query(taskId)?.apply {
                this.download = true
                // 如果status是1
                if (currTaskDetail?.status == "1") {
                    this.isReceived = true
                    toast("下载完成")
                } else {
                    toast("下载完成, 请到工作界面确认")
                }
                MyApp.roomDatabase.homeTaskDao().update(this)
                initBtnState()
            }
            EventSimple(EVENT_XML_DOWNLOAD, info = xmlFile.absolutePath).post()
            EventSimple(EVENT_HOME_TASK_REFRESH).post()
        } else {
            toast("下载失败！")
        }
    }

    private var currTaskDetail: HomeTaskDetail? = null

    private fun showProgressDialog() {
        val progress = View.inflate(context, R.layout.download_data_dialog_layout, null)
        numberProgress = progress.numberProgress
        numberProgress?.max = currTaskDetail?.length ?: 100
        dialogHelper.show(progress, false, isMath = false)
    }

    private fun getDetail(taskId: String) = launch {
        currTaskDetail = MyApp.roomDatabase.homeTaskDetailDao().query(taskId) ?: resultTryContext {
                val detail:HomeTaskDetail? = RetrofitManagement.instance.getService(Api::class.java)
                    .taskDetail(taskId).execute().body()?.data
                detail?.apply {
                    MyApp.roomDatabase.homeTaskDetailDao().insert(this)
                }
            }
        currTaskDetail?.apply {
            twoStationName?.setRightText(station)
            twoTestMember1?.setRightText(mainDebugger)
            twoTestMember2?.setRightText(slaveDebugger)
            twoStationManager?.setRightText(responsible)
            twoTimeLimit?.setRightText("${duration}天")
            twoTaskDesc?.setBottomText(explain)
        }
    }

    override fun onBackPressedSupport(): Boolean {
        pop()
        return true
    }

    override fun hasToolbar(): Boolean {
        return true
    }
}